﻿using System;
using System.Web;

namespace MuzoBlog.Core.Helpers
{
    public class CacheHelper
    {
        private static HttpContext GetHttpContext()
        {
            HttpContext httpContext = HttpContext.Current;
            if (httpContext == null)
                throw new Exception("HttpContext is null");

            return httpContext;
        }

        public static void Add<T>(T t, string key, int minute) where T : class
        {
            GetHttpContext().Cache.Insert(key, t, null, DateTime.Now.AddMinutes(minute), System.Web.Caching.Cache.NoSlidingExpiration);
        }

        public static void Clear(string key)
        {
            GetHttpContext().Cache.Remove(key);
        }

        public static bool Exists(string key)
        {
            return GetHttpContext().Cache[key] != null;
        }

        public static bool Get<T>(string key, out T value) where T : class
        {
            try
            {
                if (!Exists(key))
                {
                    value = default(T);
                    return false;
                }

                value = (T)GetHttpContext().Cache[key];
                return true;
            }
            catch
            {
                value = default(T);
                return false;
            }
        }
    }
}